import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_form_core/base_form_edit_screen.dart';
import 'package:x3_form_core/theme/base_form_theme.dart';
import 'package:x3_form_core/provider/base_request_form_provider.dart';
import 'package:x3_form_core/business_components/base_request_form_container.dart';

class BaseRequestFormLinkInput extends StatefulWidget {

  BaseRequestFormLinkInput({ Key key, @required this.request, this.requestSaveData, this.isMultipleLines = false }) : super(key: Key(request.fieldName ?? ''));

  final BaseHttpRequestModel request;

  final RequestSaveData requestSaveData;

  final bool isMultipleLines;

  @override
  _BaseRequestFormLinkInputState createState() => _BaseRequestFormLinkInputState();

}

class _BaseRequestFormLinkInputState extends State<BaseRequestFormLinkInput> {

  BaseRequestFormProvider _baseRequestFormProvider;

  String textData;

  @override
  Widget build(BuildContext context) {
    _baseRequestFormProvider = BaseRequestFormProvider.of(context);
    var _data = _baseRequestFormProvider.getDataSource(widget.request);
    var valueString;
    if (_data != null && _data is Map && _data.length != 0) {
      _data.forEach((key, value) {
        valueString = value;
      });
    } else {
      valueString = _data;
    }
    var value = valueString ?? '';
    textData = (value is String) == true ? value : value.toString();
    return BaseRequestFormContainer(
      request: widget.request,
      showSuffixIcon: !_baseRequestFormProvider.isReadonly(widget.request),
      onPress: _onLinkInputPress,
      child: _buildText(),
    );
  }

  /// 构建文本值
  Widget _buildText() {
    String text = textData.length > 0 ? textData : widget.request.notes;
    TextStyle style = textData.length > 0 ? Theme.of(context).textTheme.bodyText2 : Theme.of(context).textTheme.bodyText2.copyWith(color: BaseFormTheme.hintColor);
    return RichText(text: TextSpan(text: text, style: style), overflow: TextOverflow.ellipsis, maxLines: 1);
  }

  _onLinkInputPress() {
    widget.request.defaultValue = textData;
    BaseRouterUtil().push(BaseFormEditScreen(request: widget.request, isMultipleLines: widget.isMultipleLines,)).then((value) {
      if (value == null) return;
      setState(() {
        _baseRequestFormProvider.setDataSource(widget.request, value);
      });
      if (widget.requestSaveData != null) {
        widget.requestSaveData(widget.request, _baseRequestFormProvider.getMapDataSource(widget.request));
      }
    });
  }

}
